<?php

namespace app\enterprise\service;

use think\facade\Config;
use think\exception\ValidateException;
use app\enterprise\model\Upload as UploadModel;

class UploadService
{
    protected static $config;

    public static function init()
    {
        self::$config = Config::get('upload');
    }

    public static function upload($file)
    {
        self::init();

        // 验证文件合法性
        self::validateFile($file);

        // 上传路径或驱动
        $driver = self::$config['default'];

        switch ($driver) {
            case 'local':
                return self::uploadToLocal($file);
            case 'qiniu':
                return self::uploadToQiniu($file);
            case 'oss':
                return self::uploadToAliOss($file);
            case 'cos':
                return self::uploadToTencentCos($file);
            default:
                throw new ValidateException('不支持的上传驱动: ' . $driver);
        }
    }

    protected static function validateFile($file)
    {
        $maxSize = self::$config['filesize'];
        $allowedTypes = self::$config['fileExt'];
        $allowedMimes = self::$config['fileMime'];

        if ($file->getSize() > $maxSize) {
            throw new ValidateException('文件大小超过限制');
        }

        $ext = strtolower(pathinfo($file->getOriginalName(), PATHINFO_EXTENSION));
        if (!in_array($ext, $allowedTypes)) {
            throw new ValidateException('不允许上传此类型文件');
        }

        $mime = $file->getMime();
        if (!in_array($mime, $allowedMimes)) {
            throw new ValidateException('不允许的文件MIME类型');
        }
    }

    protected static function uploadToLocal($file)
    {
        $savePath = '/';
        $fileName = \think\facade\Filesystem::disk('public')->putFile($savePath, $file);

        $url = $fileName;

        return [
            'url' => $url,
            'name' => $file->getOriginalName(),
            'type' => 'local'
        ];
    }

    // 其他驱动上传方法略（可参考 SDK 实现）
}
